package com.wfs.myapp.remote.wx;

import com.alibaba.fastjson.JSONObject;
import com.wfs.myapp.common.Constant;
import com.wfs.myapp.remote.wx.dto.TalkAIDto;
import com.wfs.myapp.remote.wx.vo.BaiduAccessTokenVo;
import com.wfs.myapp.remote.wx.vo.BaiduTalkAiVo;
import com.wfs.myapp.utils.CaffeineUtils;
import com.wfs.myapp.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service
@Slf4j
public class BaiduRemoteService {

    private final String ACCESS_TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
    private final String SEND_MESSAGE_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=";

    @Value("${baidu.apikey}")
    private String apikey;

    @Value("${baidu.secret}")
    private String secret;

    @Autowired
    private HttpUtil httpClient;


    public BaiduAccessTokenVo getAccessToken() {
        String url = ACCESS_TOKEN_URL + "?client_id=" + apikey + "&client_secret=" + secret + "&grant_type=client_credentials";
        String s = httpClient.get(url);
        log.info("baidu get access token resp: {}", s);
        BaiduAccessTokenVo accessTokenVo = JSONObject.parseObject(s, BaiduAccessTokenVo.class);
        CaffeineUtils.put(Constant.AI_TOKEN_PRE, accessTokenVo.getAccess_token());
        return accessTokenVo;
    }

    public BaiduTalkAiVo talkAI(TalkAIDto talkAIDto) {
        String url = SEND_MESSAGE_URL + CaffeineUtils.get(Constant.AI_TOKEN_PRE);
        Map<String, String> headers = new HashMap<>();
        headers.put("Host", "aip.baidubce.com");
        String sendMessageRes = httpClient.post(url, headers, talkAIDto);
        log.info("talkAI str: {}", sendMessageRes);
        BaiduTalkAiVo sendMessageVo = JSONObject.parseObject(sendMessageRes, BaiduTalkAiVo.class);
        if (Objects.nonNull(sendMessageVo.getError_code()) && sendMessageVo.getError_code().equals(110)) {
            this.getAccessToken();
        }
        log.info("talkAIVo: {}", sendMessageVo);
        return sendMessageVo;
    }
}
